var todoData = [
  { id: '1', content: 'Sign of the Ghostly Puppet' },
  { id: '2', content: 'The Owl in the Ice' },
  { id: '3', content: 'The Prophecy in the Storm' }
];

var todoModule = (function (doc, data) {
  var oTodo = doc.getElementsByClassName('todolist')[0],
    oAdd = oTodo.getElementsByClassName('add')[0],
    oInput = oAdd.getElementsByTagName('input')[0],
    oAddBtn = oAdd.getElementsByTagName('input')[1],
    oList = oTodo.getElementsByClassName('list')[0],
    editIndex = 0;

  function render(data) {
    var tpl = ``;
    data.forEach((item) => {
      tpl += `
        <li class="item">
          <span class="content">${item.content}</span>
          <button class="edit">edit</button>
          <button class="remove">remove</button>
        </li>
      `;
    });
    oList.innerHTML = tpl;
  }

  function handleItemClick(e) {
    var e = e || window.event,
      tar = e.target || srcElement,
      className = tar.className.toLowerCase(),
      oParent = tar.parentNode,
      oItems = oList.getElementsByClassName('item'),
      curIdx = [].indexOf.call(oItems, oParent);

    switch (className) {
      case 'content':
        break;
      case 'edit':
        editItem(curIdx);
        break;
      case 'remove':
        removeItem(curIdx);
        break;
      default:
        break;
    }
  }

  function editItem(index) {
    // console.log(id, parent, data[id].content);
    oInput.value = data[index].content;
    oAddBtn.value = 'edit';
    editIndex = index;
  }

  function edit(index) {
    data[index].content = oInput.value;
    render(data);
    oAddBtn.value = 'add';
  }

  function removeItem(index) {
    data.splice(index, 1);
    render(data);
  }

  function handleAddBtnClick(e) {
    var e = e || window.event,
      tar = e.target || e.srcElement,
      btnName = tar.value;

    switch (btnName) {
      case 'add':
        addItem({
          id: new Date().getTime(),
          content: oInput.value
        });
        break;
      case 'edit':
        edit(editIndex);
        console.log('edit done');
        break;
      default:
        break;
    }

    oInput.value = '';
  }

  function addItem(item) {
    if (trimSpace(oInput.value).length === 0) return;
    todoData.unshift(item);
    render(data);
  }

  function bindEvent() {
    addEvent(oAddBtn, 'click', handleAddBtnClick);
    addEvent(oList, 'click', handleItemClick);
  }

  function init() {
    render(data);
    bindEvent();
  }

  init();
})(document, todoData);
